package com.example.springbootServiceNetwork.demos.web.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootServiceNetwork.demos.web.Config.JwtInfo;
import com.example.springbootServiceNetwork.demos.web.Config.Result;
import com.example.springbootServiceNetwork.demos.web.Config.ResultEnum;
import com.example.springbootServiceNetwork.demos.web.Dao.MenuDao;
import com.example.springbootServiceNetwork.demos.web.Dao.MenuItemDao;
import com.example.springbootServiceNetwork.demos.web.Entity.Menu;
import com.example.springbootServiceNetwork.demos.web.Entity.MenuItem;
import com.example.springbootServiceNetwork.demos.web.Service.MenuItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.util.*;

import static com.example.springbootServiceNetwork.demos.web.Tool.WrapperMethodUtil.bollPurvieTool;

@Service
public class MenuItemServiceImpl implements MenuItemService {
    @Resource
    private MenuItemDao menuItemDao;

    @Resource
    private MenuDao menuDao;


    @Resource //它定义了事务管理器的基本功能，如开始、提交、回滚事务等。
    PlatformTransactionManager platformTransactionManager;
    @Resource //它定义了事务的属性，如事务的传播行为、隔离级别、超时时间等。
    TransactionDefinition transactionDefinition;


    /**
     * 查询菜单（父类）
     */
    @Override
    public Result queryMenu(String child,JwtInfo jwtInfo){
        Result result =new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                result.setMsg(ResultEnum.SUCCESS.getData());
                result.setCode(ResultEnum.SUCCESS.getCode());
                List<Menu> list = menuDao.selectList(null);
                List<MenuItem> list2 = new ArrayList<>();
                HashMap<String,Object> map =new HashMap<>();
                if (Objects.equals(child, "true")){
                    list2 = menuItemDao.selectList(null);
                    map.put("menuItemList",list2);
                }
                map.put("menuList",list);
                result.setData(map);
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return  result;
    }

    /**
     * 新增菜单(父类)
     */
    @Override
    public Result addMenu(Menu menu, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                //查询条数
                LambdaQueryWrapper<Menu> lqw =new LambdaQueryWrapper<>();
                lqw.eq(Menu::getMenuMark,menu.getMenuMark());
                //查询总数
                int count = Math.toIntExact(menuDao.selectCount(lqw));
                String menuCode = menu.getMenuMark();
                if (count>=1){
                    List<Menu> list =menuDao.selectList(lqw);
                    String[] arrNum = new String[0];
                    if(!list.isEmpty()){
                        arrNum =list.get(count-1).getMenuCode().split(menu.getMenuMark());
                    }
                    if (arrNum.length>1){
                        int number = Integer.parseInt(arrNum[1]);
                        if (number<9&&number>=0){
                            menuCode=menuCode+"00"+(number+1);
                        }else if (number<99&&number>=9){
                            menuCode=menuCode+"0"+(number+1);
                        }else  if (number<999&&number>=99){
                            menuCode=menuCode+"0"+(number+1);
                        }else {
                            menuCode=menuCode+"1000";
                        }
                    }else {
                        menuCode=menuCode+"001";
                    }
                }else {
                    menuCode=menuCode+"001";
                }

                //创建时间
                menu.setCreateTime(new Date());
                //菜单编码
                menu.setMenuCode(menuCode);
                if (menu.getMenuName()==null){
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg(ResultEnum.BADREQUEST.getData());
                }else {
                    int res =menuDao.insert(menu);
                    if (res==1){
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg(ResultEnum.SUCCESS.getData());
                    }else {
                        result.setCode(ResultEnum.BADREQUEST.getCode());
                        result.setMsg(ResultEnum.BADREQUEST.getData());
                    }
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }

    /**
     * 修改菜单(父类)
     */
    @Override
    public Result updateMenu(Menu menu, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                int res=menuDao.updateById(menu);
                if (res==1){
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg(ResultEnum.SUCCESS.getData());
                }else {
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg(ResultEnum.BADREQUEST.getData());
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }

        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }
    /**
     * 删除菜单(父类)
     */
    @Override
    public Result deleteMenu(Menu menu, JwtInfo jwtInfo){
        Result result = new Result();
        TransactionStatus transactionStatus=platformTransactionManager.getTransaction(transactionDefinition);
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                int res=menuDao.deleteById(menu);
                if (res==1&&!(menu.getMenuCode()==null)){
                    LambdaQueryWrapper<MenuItem> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(MenuItem::getParentCode,menu.getMenuCode());
                    lqw.eq(MenuItem::getParentId,menu.getId());
                    List<MenuItem> listItem = menuItemDao.selectList(lqw);
                    int delNum = 0;
                    for (MenuItem item :listItem) {
                        int res2 = menuItemDao.deleteById(item);
                        delNum = delNum+res2;
                    }
                    if (listItem.size()==delNum){
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg(ResultEnum.SUCCESS.getData());
                        platformTransactionManager.commit(transactionStatus);
                    }else {
                        platformTransactionManager.rollback(transactionStatus);
                        result.setCode(ResultEnum.BADREQUEST.getCode());
                        result.setMsg("删除失败！");
                    }
                }else {
                    platformTransactionManager.rollback(transactionStatus);
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg("删除失败！");
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }

    /**
     * 查询菜单接口（子类）
     */
    @Override
    public Result queryMenuItem(MenuItem menuItem, JwtInfo jwtInfo){
        Result result =new Result();
        try {
            LambdaQueryWrapper<MenuItem>lqw=new LambdaQueryWrapper<>();
            lqw.eq(MenuItem::getParentCode,menuItem.getParentCode());
            lqw.eq(MenuItem::getParentId,menuItem.getParentId());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setMsg("菜单查询成功");
            if (jwtInfo.getPass()){
                List<MenuItem> itemList =menuItemDao.selectList(lqw);
                List<MenuItem> resList =new ArrayList<>();
                for (MenuItem item:itemList){
                    for (String item2:jwtInfo.getPurview()){
                        if (item2.contains(item.getMenuPurview())){
                            resList.add(item);
                        }
                    }
                }
                result.setData(resList);
            }else {
                lqw.eq(MenuItem::getMenuPurview,"ordinary");
                List<MenuItem> itemList =menuItemDao.selectList(lqw);
                result.setData(itemList);
            }

        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }
    /**
     * 新增菜单(子类)
     */
    @Override
    public Result addMenuItem(MenuItem menuItem, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            LambdaQueryWrapper<MenuItem> lqw =new LambdaQueryWrapper<>();
            lqw.eq(MenuItem::getParentId,menuItem.getParentId());
            lqw.eq(MenuItem::getParentCode,menuItem.getParentCode());
            int count = Math.toIntExact(menuItemDao.selectCount(lqw));
            List<MenuItem> list = menuItemDao.selectList(lqw);
            int menuId = 1;
            if (!list.isEmpty()){
                 menuId = list.get(count-1).getMenuId() +1;
            }
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                //更新时间
                menuItem.setCreateTime(new Date());
                //更新菜单序号id
                menuItem.setMenuId(menuId);
                //菜单访问权限
                if (menuItem.getMenuPurview()==null){
                    menuItem.setMenuPurview("ordinary");
                }
                //菜单状态
                menuItem.setMenuStatus(1);

                if (menuItem.getMenuName()==null){
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg("菜单名称不能为空！");
                }else {
                    int res =menuItemDao.insert(menuItem);
                    if (res==1){
                        result.setCode(ResultEnum.SUCCESS.getCode());
                        result.setMsg(ResultEnum.SUCCESS.getData());
                    }else {
                        result.setCode(ResultEnum.BADREQUEST.getCode());
                        result.setMsg(ResultEnum.BADREQUEST.getData());
                    }
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }

    /**
     * 修改菜单(子类)
     */
    @Override
    public Result updateMenuItem(MenuItem menuItem, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                int res=menuItemDao.updateById(menuItem);
                if (res==1){
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg(ResultEnum.SUCCESS.getData());
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }

        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }
    /**
     * 删除菜单(子类)
     */
    @Override
    public Result deleteMenuItem(MenuItem menuItem, JwtInfo jwtInfo){
        Result result = new Result();
        try {
            if (bollPurvieTool(jwtInfo.getPurview(),"superAdmin" )){
                int res=menuItemDao.deleteById(menuItem);
                if (res==1){
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg(ResultEnum.SUCCESS.getData());
                }else {
                    result.setCode(ResultEnum.BADREQUEST.getCode());
                    result.setMsg("删除失败！");
                }
            }else {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("您暂无权限！");
            }
        }catch (Exception e){
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg(ResultEnum.UNKNOWNERROR.getData());
            result.setData(e);
        }
        return result;
    }


}
